<?php
namespace app\controller;

use app\BaseController;
use app\model\index\Web;
use think\Exception;
use think\facade\Db;
use think\facade\View;

class Index extends BaseController
{
    public function index()
    {
        return View::fetch('/home');
    }

    public function web($url = '',$id = 0,$type = 1){
        $where = [];
        $get = input('get.');
        !empty($get['classify']) && $where[] = ['classify','=',$get['classify']];
        if (!empty($url)){
            $css = $cssw = $js = '';
            $uniqid = md5($url).$id;
            $temp = cache($uniqid);
            header('Content-Type: text/html; charset=UTF-8');
            if (!empty($temp))die($temp);
            $html = @file_get_contents($url);
            if (strpos($html,'charset=gb2312') !== false) {
                $html = str_replace('charset=gb2312','charset=UTF-8',$html);
                $html = mb_convert_encoding($html, 'UTF-8', 'gb2312');
            }
            // 正则表达式模式，匹配具有charset属性的<meta>标签
//            $pattern = '/<meta\s+(?:[^>]*?\s+)?charset=["\']?(?:[\w-]+)["\']?(?:[^>]*)>/i';
            // 使用preg_replace函数移除匹配的标签
//            $html = preg_replace($pattern, '', $html);
            $parsedUrl = parse_url($url);
            $url = 'http://'.$parsedUrl['host'];
            $html = preg_replace('/(href|src)="([^"]+)"/', '$1="' . $url . '/$2"', $html);
            // 正则表达式模式，用于匹配 <link> 标签中的 href 属性，且 rel 属性为 stylesheet（不区分大小写）
            $pattern = '/<link\s+(?:[^>]*?\s+)?href=["\']([^"\']+)["\'](?:[^>]*?)(?:\s+rel=["\']stylesheet["\'])?[^>]*>/i';
            // 使用 preg_match_all 函数查找所有匹配项
            $html = str_replace($url.'/'.$url,$url,$html);
            preg_match_all($pattern, $html, $matches);
            // $matches[1] 包含所有捕获的 href 属性值
            $css_links = $matches[1];
            // dd($css_links);
            foreach ($css_links AS $key => $value){
                $cssw = @file_get_contents($value);
                if (empty($cssw))continue;
                $cssw = @preg_replace_callback(
                    '/url\([\'"]?([^\'")]+)[\'"]?\)/',
                    function ($matches) use ($value) {
                        // 提取出的相对 URL（去掉引号，但保留斜杠）
                        $relativeUrl = $matches[1];
                        // 拼接完整的 URL（注意保留原有的斜杠）
                        $fullUrl = dirname($value) . '/' . ltrim($relativeUrl, '/');
                        // 返回替换后的 URL 字符串
                        return "url('" . $fullUrl . "')";
                    },
                    $cssw
                );
                $cssw = str_replace('.slideBox .bd{ position:relative; height:100%; z-index:0;   }','.slideBox .bd{position:relative;/* height:100%; */z-index:0;}',$cssw);
                $css .= $cssw;
            }
            $css_links = $matches[0];
            foreach ($css_links AS $key => $value){
                $html = str_replace($value,'',$html);
            }
            @file_put_contents('./css/'.$uniqid.'.css',$css);
            $pattern = '/<script\s+[^>]*?src=[\'"]([^\'"]+)[\'"].*?<\/script>/i';
            preg_match_all($pattern, $html, $matches);
            // $matches[1] 包含所有捕获的 src 属性值
            $js_srcs = $matches[1];
            $js_del = $matches[0];
            foreach ($js_srcs AS $key => $value){
                $jsm = @file_get_contents($value);
                $js = @file_put_contents('./js/'.$uniqid.$key.'.js',$jsm);
            }
            foreach ($js_del AS $key => $value){
                $html = str_replace($value,'<script src="/js/'.$uniqid.$key.'.js"></script>',$html);
            }
            $html = '<link rel="stylesheet" href="https://so.wzscwl.com/css/'.$uniqid.'.css">'.$html;
            // $html = $js.$html;
            // 正则表达式匹配 <a> 标签及其 href 属性
            $pattern = '/<a\s+(?:[^>]*?\s+)?href="(?!\/)([^"]*)"[^>]*>(.*?)<\/a>/is';
            // 使用 preg_replace_callback 遍历所有匹配项
            $html = preg_replace_callback($pattern, function ($matches) use($id,$url){
                $originalUrl = $matches[1];
                if (strpos($originalUrl,$url) === false)
                    $originalUrl = $url.'/'.$originalUrl;
                $newUrl = 'https://so.wzscwl.com/web?url=' . urlencode($originalUrl) . '&type=2&id='.$id;
                $replacedTag = str_replace('href="'.$matches[1], 'href="'.$newUrl, $matches[0]);
                return $replacedTag;
            }, $html);
            $html = str_replace('href="/"','href="https://so.wzscwl.com/web?url='.$url.'&id="'.$id,$html);
            // $html = htmlspecialchars_decode($modifiedHtml);
            //   file_put_contents('/'.$id.'.html',$html);
            $pattern = '/src=[\'"]?([^\'"\s]+?\.(jpg|png|gif))[\'"]?/i';
            @preg_match_all($pattern, $html, $matches);
            // dd($matches);
            foreach ($matches[1] AS $key => $value){
                $result = md5($value).'.png';
                $path = './images/'.$id.'/'.$result;
                if (!file_exists($path)) {
                    $ch = curl_init();
                    // 设置 cURL 选项，包括 URL 和返回结果作为字符串而不是直接输出
                    curl_setopt($ch, CURLOPT_URL, $value);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 允许重定向
                    // 执行 cURL 会话并获取图片内容
                    $imageData = curl_exec($ch);
                    curl_close($ch);
                    // dd($imageData);
                    $base64 = 'data:' . curl_getinfo($ch, CURLINFO_CONTENT_TYPE) . ';base64,' . base64_encode($imageData);
                    // $imageData = base64_decode($base64);
                    is_dir('./images/' . $id) || mkdir('./images/' . $id);
                    // dd($path);
                    @file_put_contents($path, $imageData);
                }
                $html = str_replace($value,'https://so.wzscwl.com'.substr($path,1),$html);
            }
            cache($uniqid,$html,864000);
            // file_put_contents('');
            die($html);
        }
        $web = Db::name('web')
            ->where($where)
            ->select()
            ->toArray();
        return View::fetch('/web',['web' => $web]);
    }

    public function home(){
        $url = input('url');
        $find = Db::name('web')->where('id',$url)->find();
        return View::fetch('/index/home',['id' => $find['id'],'url' => $find['web'] ?? '','name' => $find['name'] ?? '']);
    }

    public function hello($name = 'ThinkPHP6')
    {
        $data = Db::name('qipei_goods')->where('id','<',50)->select();
        foreach ($data AS $key => $value){
            foreach ($value AS $index => $item) {
                $item = strip_tags($item);
                $item = str_replace('\\n','',$item);
                $value[$index] = $item;
            }
//            dd($value);
            Db::name('qipei_goods')->where('id',$value['id'])->save($value);
            sleep(1);
        }
        return 'hello,' . $name;
    }
    public function address($parent_code = 0,$name = ''){
        if (!empty($name)){
            $address = Db::name('address')
                ->where('parent_code', function($sql) use ($name){
                    $sql->name('address')->field('code')->where('name','like',$name)->select();
                })
                ->select();
        }else {
            $address = Db::name('address')->where('parent_code', $parent_code)->select();
        }
        return $address;
    }
    public function get_data_index(){
        return View::fetch('/get_data_index');
    }
    
    public function email(){
        $get = input('get.');
        $thead = $tbody = '';
        $message = [];
        @file_put_contents('./email.log',"-------\n".json_encode($get),1);
        if ($get['web'] == 'cdyoo'){
            $array = ['name' => '留言用户姓名','tel' => '留言用户手机号','content' => '留言内容'];
            $title = '用户留言转发邮件';
        }
        foreach ($array AS $key => $value){
            $thead .= '<td>'.$value.'</td>';
        }
        foreach ($array AS $key => $value){
            if (!empty($get[$key]))
                $tbody .= '<td>'.$get[$key].'</td>';
        }
        $thead = '<tr>'.$thead.'</tr>';
        $tbody = '<tr>'.$tbody.'</tr>';
        $body = file_get_contents(public_path() . '/../view/index/email.html');
        $body = str_replace('{head}', $thead, $body);
        $body = str_replace('{content}', $tbody, $body);
        $this->send('1213378232@qq.com', $title, $body);
        $this->send('crystal@chengde-flange.com', $title, $body);
        var_dump($get);
        die;
    }

    private function send($email,$title = '',$body = ''){
        $message = new \Swift_Message($title);
        $message = $message->setFrom('ppf1788@sina.com');
        $message = $message->setTo($email);
        $message = $message->setBody($body,'text/html' );
        $transport = new \Swift_SmtpTransport('smtp.sina.com', 465,'ssl');
        $transport = $transport->setUsername('ppf1788@sina.com');
        $transport = $transport->setPassword('14c1f2883d0b344e');
        $mailer = new \Swift_Mailer($transport);
        $mailer->send($message);
        //return json(['code' => 200,'msg' => '成功','data' => $res],200);
    }
}
